from django.conf import settings
from django import forms
from django.utils.encoding import StrAndUnicode, force_unicode
from django.utils.safestring import mark_safe
from django.forms.util import flatatt
import datetime

from komponents.ajax.widgets import AjaxInput

class DateWidget(AjaxInput, forms.DateTimeInput):
    format = '%d-%m-%Y'     # '2006-10-25 14:30:59'
    format = settings.DATE_FORMAT
    class Media:
        js = (settings.MEDIA_URL + "/js/calendar.js",
              settings.MEDIA_URL + "/js/DateTimeShortcuts.js")

    def __init__(self, attrs={}):
        super(DateWidget, self).__init__(attrs={'class': 'vDateField', 'size': '10'})
    
class TimeWidget(AjaxInput, forms.TextInput):
    class Media:
        js = (settings.MEDIA_URL + "/js/calendar.js",
              settings.MEDIA_URL + "/js/DateTimeShortcuts.js")

    def __init__(self, attrs={}):
        super(TimeWidget, self).__init__(attrs={'class': 'vTimeField', 'size': '8'})

class CalendarWidget(AjaxInput, forms.DateInput):
    #format = '%d-%m-%Y'     # '2006-10-25 14:30:59'
    format = settings.DATE_FORMAT
    
    CODE=r"""
    <script type="text/javascript">
        $(function() {
            $("#%(id)s").dynDateTime({
                showsTime: false,
                ifFormat: "%(format)s",
                daFormat: "%%Y",
                align: "BR",
                electric: true,
                singleClick: true            
            });
        });
    </script>
    """    
    class Media:        
        js = (
             # settings.MEDIA_URL + "komponents/js/jquery/jquery-1.3.2.min.js",
              settings.MEDIA_URL + "/komponents/js/jquery.dynDateTime-0.2/jquery.dynDateTime.pack.js",
              settings.MEDIA_URL + "/komponents/js/jquery.dynDateTime-0.2/lang/calendar-en.js",
              settings.MEDIA_URL + "/komponents/js/jquery.dynDateTime-0.2/lang/calendar-it.pack.js"
              )
        css = {'screen':( settings.MEDIA_URL + "/komponents/js/jquery.dynDateTime-0.2/css/calendar-win2k-cold-1.css",) }
        pass
    
    def __init__(self, attrs={}):
        super(CalendarWidget, self).__init__(attrs={ 'size': '10','autocomplete':'off'})

    def render(self, name, value=None, attrs=None):
        final_attrs = self.build_attrs(attrs, name=name, type=self.input_type)
        final_attrs['format'] = self.format
        ret= super(CalendarWidget, self).render(name, value, attrs)
        
        c = self.CODE % final_attrs
        
        return mark_safe(ret + c)
        
    
# -*- coding: utf-8 -*-
# widgets.py
#
# To use you have to put calendar/ (from http://www.dynarch.com/projects/calendar/)
# to your MEDIA folder and then include such links on your page:
# <!-- calendar -->
# <link rel="stylesheet" type="text/css" href="{{ MEDIA_URL }}calendar/calendar-win2k-cold-2.css" />
#<script type="text/javascript" src="{{ MEDIA_URL }}calendar/calendar.js"></script>
# <!-- this is translation file - choose your language here -->
#<script type="text/javascript" src="{{ MEDIA_URL }}calendar/lang/calendar-pl.js"></script>
#<script type="text/javascript" src="{{ MEDIA_URL }}calendar/calendar-setup.js"></script>
#<!-- /calendar -->

from django.utils.encoding import force_unicode
from django.conf import settings
from django import forms
from datetime import datetime
import  time

# DATETIMEWIDGET
calbtn = u"""<img src="%simages/calbutton.gif" alt="calendar" id="%s_btn" style="cursor: pointer; border: 1px solid #8888aa;" title="Select date and time"
            onmouseover="this.style.background='#444444';" onmouseout="this.style.background=''" />
<script type="text/javascript" defer="defer"><!--
    Calendar.setup({
        inputField     :    "%s",
        ifFormat       :    "%s",
        button         :    "%s_btn",
        singleClick    :    true,
        showsTime      :    true
    });
--></script>"""

class DateWidget2(forms.widgets.TextInput):
    dformat = '%Y-%m-%d %H:%M'
    def render(self, name, value, attrs=None):
        if value is None: value = ''
        final_attrs = self.build_attrs(attrs, type=self.input_type, name=name)
        if value != '': 
            try:
                final_attrs['value'] = \
                                   force_unicode(value.strftime(self.dformat))
            except:
                final_attrs['value'] = \
                                   force_unicode(value)
        if not final_attrs.has_key('id'):
            final_attrs['id'] = u'%s_id' % (name)
        id = final_attrs['id']
        
        jsdformat = self.dformat #.replace('%', '%%')
        cal = calbtn % (settings.MEDIA_URL, id, id, jsdformat, id)
        a = u'<input%s />%s' % (forms.util.flatatt(final_attrs), cal)
        return a

    def value_from_datadict(self, data, files, name):
        dtf = forms.fields.DEFAULT_DATETIME_INPUT_FORMATS
        empty_values = forms.fields.EMPTY_VALUES

        value = data.get(name, None)
        if value in empty_values:
            return None
        if isinstance(value, datetime.datetime):
            return value
        if isinstance(value, datetime.date):
            return datetime.datetime(value.year, value.month, value.day)
        for format in dtf:
            try:
                return datetime.datetime(*time.strptime(value, format)[:6])
            except ValueError:
                continue
        return None
    
    